extends RefCounted
class_name TempSaveMgr
##本脚本通过PackedScene实现局内临时保存绝大多数单位的状态，便于局内的状态回档。
##特别是单位已经被Spawner回收重置的状况下。

var cemetery:Dictionary[String,Array] = {}

func save_node(node:Node):
	var tombstone:Array[PackedScene] =  _create_tombstone(node.scene_file_path)
	var scene:PackedScene = PackedScene.new()
	scene.pack(node)
	tombstone.append(scene)
	cemetery[node.scene_file_path] = tombstone

func _create_tombstone(node_path:String)->Array[PackedScene]:
	var tombstone:Array[PackedScene] = []
	cemetery[node_path] = tombstone
	return tombstone

func get_last_node(node_path:String,permanent:bool = false)->Node:
	var scene:PackedScene = cemetery[node_path].back()
	if permanent:
		erase_node(node_path,scene)
	var node = scene.instantiate()
	return node

func get_first_node(node_path:String,permanent:bool = false)->Node:
	var scene:PackedScene = cemetery[node_path].front()
	if permanent:
		erase_node(node_path,scene)
	var node = scene.instantiate()
	return node

func get_random_node(node_path:String,permanent:bool = false)->Node:
	var scene:PackedScene = cemetery[node_path].pick_random()
	if permanent:
		erase_node(node_path,scene)
	var node = scene.instantiate()
	return node

func erase_node(path:String,scene:PackedScene):
	cemetery[path].erase(scene)
